﻿package net.wangit.util;

import java.io.UnsupportedEncodingException;

public class BIG5Util {

	public BIG5Util() {
	}

	public static String get(String content, String encoding) {
		if (encoding.equals("GBK"))
			return content;
		else
			return GB2BIG5(content);
	}

	private static boolean isBIG5(int in1, int in2) {
		boolean Result = true;
		if (in1 < 161 && (in2 < 64 || in2 > 126) && (in2 < 161 || in2 > 254))
			Result = false;
		return Result;
	}

	public static String GB2BIG5(String strIn) {
		String strOut = "";
		int in1 = 0;
		int in2 = 0;
		String BIG5Code = "";
		try {
			byte listIn[] = strIn.getBytes("gb2312");
			for (int ii = 0; ii < listIn.length - 1; ii++) {
				in1 = listIn[ii] & 0xff;
				in2 = listIn[ii + 1] & 0xff;
				if (in1 >= 129 && in1 <= 254
						&& (in2 >= 64 && in2 < 127 || in2 > 127 && in2 <= 254)) {
					BIG5Code = GBCode.getCode(getGBOrder(in1, in2));
					listIn[ii] = (byte) Integer.parseInt(BIG5Code.substring(0,
							2), 16);
					listIn[ii + 1] = (byte) Integer.parseInt(BIG5Code
							.substring(2, 4), 16);
					ii++;
				}
			}

			strOut = new String(listIn, "big5");
		} catch (UnsupportedEncodingException unsupportedencodingexception) {
		}
		return strOut;
	}

	private static int getGBOrder(int in1, int in2) {
		return (in1 - 161) * 94 + (in2 - 161);
	}

	private static int getBIG5Order(int in1, int in2) {
		if (in2 >= 64 && in2 <= 126)
			return (in1 - 161) * 157 + (in2 - 64);
		else
			return (in1 - 161) * 157 + 63 + (in2 - 161);
	}

	public static String BIG52GB(String strIn) {
		String strOut = "";
		int in1 = 0;
		int in2 = 0;
		String GBCode = "";
		try {
			byte listIn[] = strIn.getBytes("big5");
			for (int ii = 0; ii < listIn.length - 1; ii++) {
				in1 = listIn[ii] & 0xff;
				in2 = listIn[ii + 1] & 0xff;
				if (in1 >= 129 && in1 <= 254
						&& (in2 >= 64 && in2 < 127 || in2 > 127 && in2 <= 254)
						&& isBIG5(in1, in2)) {
					GBCode = BIG5Code.getCode(getBIG5Order(in1, in2));
					listIn[ii] = (byte) Integer.parseInt(
							GBCode.substring(0, 2), 16);
					listIn[ii + 1] = (byte) Integer.parseInt(GBCode.substring(
							2, 4), 16);
					ii++;
				}
			}

			strOut = new String(listIn, "gb2312");
		} catch (UnsupportedEncodingException unsupportedencodingexception) {
		}
		return strOut;
	}
}
